package com.example.handheld4_gsignal_app.ui.fragments;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.handheld4_gsignal_app.R;
import com.example.handheld4_gsignal_app.data.SignalRecord;
import com.example.handheld4_gsignal_app.services.HistoryService;
import com.example.handheld4_gsignal_app.services.DataExportService;
import com.example.handheld4_gsignal_app.services.DataAnalysisService;
import com.google.gson.Gson;

import java.io.File;
import androidx.core.content.FileProvider;
import java.util.ArrayList;
import java.util.List;

/**
 * 历史记录Fragment - 显示采集历史数据，支持查询、导出、分析功能
 */
public class HistoryFragment extends Fragment {

    private ListView historyListView;
    private Spinner filterSpinner;
    private ArrayAdapter<String> historyAdapter;
    private HistoryService historyService;
    private DataExportService exportService;
    private DataAnalysisService analysisService;
    private List<SignalRecord> signalRecords;
    
    // 新增的UI组件
    private Button btnExportData;
    private Button btnAnalyzeData;
    private Button btnShowCharts;
    private TextView tvTotalRecords;
    private TextView tvAvgSignal;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            android.util.Log.d("HistoryFragment", "onCreateView started");
            View view = inflater.inflate(R.layout.fragment_history, container, false);
            android.util.Log.d("HistoryFragment", "Layout inflated successfully");
            
            initViews(view);
            android.util.Log.d("HistoryFragment", "Views initialized");
            
            setupFilterSpinner();
            android.util.Log.d("HistoryFragment", "Filter spinner setup");
            
            initServices();
            android.util.Log.d("HistoryFragment", "Services initialized");
            
            setupClickListeners();
            android.util.Log.d("HistoryFragment", "Click listeners setup");
            
            loadHistoryData();
            android.util.Log.d("HistoryFragment", "History data loaded");
            
            updateStatistics();
            android.util.Log.d("HistoryFragment", "Statistics updated");
            
            return view;
        } catch (Exception e) {
            android.util.Log.e("HistoryFragment", "Error in onCreateView: " + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 初始化视图组件
     */
    private void initViews(View view) {
        try {
            historyListView = view.findViewById(R.id.history_list_view);
            filterSpinner = view.findViewById(R.id.filter_spinner);
            btnExportData = view.findViewById(R.id.btn_export_data);
            btnAnalyzeData = view.findViewById(R.id.btn_analyze_data);
            btnShowCharts = view.findViewById(R.id.btn_show_charts);
            tvTotalRecords = view.findViewById(R.id.tv_total_records);
            tvAvgSignal = view.findViewById(R.id.tv_avg_signal);
            
            // 优化ListView滚动体验
            if (historyListView != null) {
                // 启用垂直滚动条
                historyListView.setVerticalScrollBarEnabled(true);
                // 设置滚动条样式
                historyListView.setScrollBarStyle(android.view.View.SCROLLBARS_OUTSIDE_OVERLAY);
                // 禁用滚动条淡出效果，保持可见
                historyListView.setScrollbarFadingEnabled(false);
                // 设置快速滚动
                historyListView.setFastScrollEnabled(true);
                // 设置滚动条大小
                historyListView.setScrollBarSize(8);
                // 启用嵌套滚动支持
                historyListView.setNestedScrollingEnabled(true);
                // 设置过度滚动模式
                historyListView.setOverScrollMode(android.view.View.OVER_SCROLL_ALWAYS);
                // 设置选择模式
                historyListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                // 启用点击效果
                historyListView.setClickable(true);
                // 设置缓存颜色提示
                historyListView.setCacheColorHint(android.graphics.Color.TRANSPARENT);
                // 设置滚动监听器
                historyListView.setOnScrollListener(new android.widget.AbsListView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(android.widget.AbsListView view, int scrollState) {
                        // 滚动状态改变时的处理
                    }

                    @Override
                    public void onScroll(android.widget.AbsListView view, int firstVisibleItem, 
                                       int visibleItemCount, int totalItemCount) {
                        // 滚动过程中的处理
                    }
                });
            }
            
            // 检查关键组件是否找到
            if (historyListView == null) {
                android.util.Log.e("HistoryFragment", "historyListView is null");
            }
            if (filterSpinner == null) {
                android.util.Log.e("HistoryFragment", "filterSpinner is null");
            }
            if (btnExportData == null) {
                android.util.Log.e("HistoryFragment", "btnExportData is null");
            }
            if (btnAnalyzeData == null) {
                android.util.Log.e("HistoryFragment", "btnAnalyzeData is null");
            }
            if (btnShowCharts == null) {
                android.util.Log.e("HistoryFragment", "btnShowCharts is null");
            }
            if (tvTotalRecords == null) {
                android.util.Log.e("HistoryFragment", "tvTotalRecords is null");
            }
            if (tvAvgSignal == null) {
                android.util.Log.e("HistoryFragment", "tvAvgSignal is null");
            }
        } catch (Exception e) {
            android.util.Log.e("HistoryFragment", "Error in initViews: " + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 设置过滤器下拉框
     */
    private void setupFilterSpinner() {
        try {
            android.util.Log.d("HistoryFragment", "setupFilterSpinner started");
            String[] filterOptions = {"全部", "今天", "本周", "本月"};
            ArrayAdapter<String> filterAdapter = new ArrayAdapter<>(getContext(), 
                android.R.layout.simple_spinner_item, filterOptions);
            filterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            filterSpinner.setAdapter(filterAdapter);
            android.util.Log.d("HistoryFragment", "setupFilterSpinner completed");
        } catch (Exception e) {
            android.util.Log.e("HistoryFragment", "Error in setupFilterSpinner: " + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 初始化服务
     */
    private void initServices() {
        historyService = new HistoryService(getContext());
        exportService = new DataExportService(getContext());
        analysisService = new DataAnalysisService(getContext());
        signalRecords = new ArrayList<>();
    }

    /**
     * 设置点击监听器
     */
    private void setupClickListeners() {
        btnExportData.setOnClickListener(v -> exportData());
        btnAnalyzeData.setOnClickListener(v -> analyzeData());
        btnShowCharts.setOnClickListener(v -> showCharts());
        
        filterSpinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                refreshData();
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {
                // 不做处理
            }
        });
    }

    /**
     * 加载历史数据
     */
    private void loadHistoryData() {
        if (historyService != null) {
            // 使用与refreshData相同的逻辑来设置时间范围
            int selectedPosition = filterSpinner.getSelectedItemPosition();
            String filter = filterSpinner.getSelectedItem().toString();
            
            // 根据过滤器设置时间范围
            String startTime = null;
            String endTime = null;
            
            switch (filter) {
                case "今天":
                    startTime = getTodayStartTime();
                    endTime = getTodayEndTime();
                    break;
                case "本周":
                    startTime = getWeekStartTime();
                    endTime = getWeekEndTime();
                    break;
                case "本月":
                    startTime = getMonthStartTime();
                    endTime = getMonthEndTime();
                    break;
                default:
                    // 全部数据，不设置时间限制
                    break;
            }
            
            // 从服务器获取历史数据
            String deviceId = "DEVICE_001"; // 可以从设置或用户信息中获取
            int limit = 100;         // 限制100条记录
            int offset = 0;          // 从第一条开始
            
            historyService.fetchHistoryDataFromServer(deviceId, startTime, endTime, limit, offset,
                    new HistoryService.HistoryCallback() {
                @Override
                public void onSuccess(List<SignalRecord> records) {
                    // 在主线程中更新UI
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            signalRecords = records;
                            updateHistoryList();
                            updateStatistics();
                        });
                    }
                }
                
                @Override
                public void onError(String error) {
                    // 在主线程中显示错误信息
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "加载历史数据失败: " + error, Toast.LENGTH_LONG).show();
                            // 如果服务器查询失败，使用本地数据
                            signalRecords = historyService.getAllRecords();
                            updateHistoryList();
                            updateStatistics();
                        });
                    }
                }
            });
        }
    }

    /**
     * 更新历史记录列表
     */
    private void updateHistoryList() {
        if (signalRecords == null || signalRecords.isEmpty()) {
            // 如果没有数据，显示空状态
            List<String> emptyItems = new ArrayList<>();
            emptyItems.add("暂无历史记录");
            historyAdapter = new ArrayAdapter<>(getContext(), 
                android.R.layout.simple_list_item_1, emptyItems);
            historyListView.setAdapter(historyAdapter);
            return;
        }

        // 使用自定义适配器显示美观的历史记录
        HistoryAdapter customAdapter = new HistoryAdapter(signalRecords);
        historyListView.setAdapter(customAdapter);
    }
    
    /**
     * 自定义历史记录适配器
     */
    private class HistoryAdapter extends BaseAdapter {
        private List<SignalRecord> records;
        
        public HistoryAdapter(List<SignalRecord> records) {
            this.records = records;
        }
        
        @Override
        public int getCount() {
            return records.size();
        }
        
        @Override
        public Object getItem(int position) {
            return records.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.item_collection_history, parent, false);
                holder = new ViewHolder();
                holder.tvCollectionTime = convertView.findViewById(R.id.tvCollectionTime);
                holder.tvSignalStrength = convertView.findViewById(R.id.tvSignalStrength);
                holder.tvLocation = convertView.findViewById(R.id.tvLocation);
                holder.tvNetworkType = convertView.findViewById(R.id.tvNetworkType);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            
            SignalRecord record = records.get(position);
            
            // 设置时间
            holder.tvCollectionTime.setText("🕐 " + record.getCollectedAt());
            
            // 设置信号强度，根据强度显示不同颜色
            int signalStrength = record.getSignalStrength();
            holder.tvSignalStrength.setText("📶 " + signalStrength + " dBm");
            
            // 设置位置信息
            holder.tvLocation.setText("📍 " + String.format("%.4f, %.4f", 
                record.getLatitude(), record.getLongitude()));
            
            // 设置网络类型
            String networkType = record.getNetworkType() != null ? record.getNetworkType() : "未知";
            holder.tvNetworkType.setText("📡 " + networkType);
            
            return convertView;
        }
        
        class ViewHolder {
            TextView tvCollectionTime;
            TextView tvSignalStrength;
            TextView tvLocation;
            TextView tvNetworkType;
        }
    }

    /**
     * 更新统计信息
     */
    private void updateStatistics() {
        if (signalRecords != null && !signalRecords.isEmpty()) {
            tvTotalRecords.setText(String.valueOf(signalRecords.size()));
            
            // 计算平均信号强度 - 使用传统循环避免Stream API兼容性问题
            int totalSignal = 0;
            for (SignalRecord record : signalRecords) {
                totalSignal += record.getSignalStrength();
            }
            double avgSignal = (double) totalSignal / signalRecords.size();
            tvAvgSignal.setText(String.format("%.1f dBm", avgSignal));
        } else {
            tvTotalRecords.setText("0");
            tvAvgSignal.setText("0 dBm");
        }
    }

    /**
     * 导出数据
     */
    private void exportData() {
        if (signalRecords == null || signalRecords.isEmpty()) {
            Toast.makeText(getContext(), "没有数据可导出", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            String filePath = exportService.exportToCSV(signalRecords);
            Toast.makeText(getContext(), "数据已导出到: " + filePath, Toast.LENGTH_LONG).show();
            
            // 使用FileProvider安全地共享文件
            File file = new File(filePath);
            if (file.exists()) {
                Uri fileUri = FileProvider.getUriForFile(
                    getContext(),
                    getContext().getPackageName() + ".fileprovider",
                    file
                );
                
                // 直接使用文件选择器，让用户选择应用
            Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(fileUri, "*/*"); // 使用通用MIME类型
                
                // 创建选择器
                Intent chooserIntent = Intent.createChooser(intent, "选择应用打开CSV文件");
                chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                
                try {
                    startActivity(chooserIntent);
                } catch (Exception e) {
                    // 如果选择器失败，尝试直接打开
                    try {
                        intent.setDataAndType(fileUri, "text/csv");
                        startActivity(intent);
                    } catch (Exception e2) {
                        try {
                            intent.setDataAndType(fileUri, "application/csv");
                            startActivity(intent);
                        } catch (Exception e3) {
                            try {
                                intent.setDataAndType(fileUri, "text/plain");
            startActivity(intent);
                            } catch (Exception e4) {
                                Toast.makeText(getContext(), 
                                    "无法打开文件。请手动到文件管理器找到文件: " + filePath + 
                                    "\n建议安装WPS Office、Microsoft Office或Google Sheets", 
                                    Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                }
            } else {
                Toast.makeText(getContext(), "导出文件不存在: " + filePath, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(getContext(), "导出失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 分析数据
     */
    private void analyzeData() {
        if (signalRecords == null || signalRecords.isEmpty()) {
            Toast.makeText(getContext(), "没有数据可分析", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            String analysisResult = analysisService.analyzeSignalData(signalRecords);
            showAnalysisDialog(analysisResult);
        } catch (Exception e) {
            Toast.makeText(getContext(), "分析失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示分析结果对话框
     */
    private void showAnalysisDialog(String analysisResult) {
        try {
            new androidx.appcompat.app.AlertDialog.Builder(getContext())
                .setTitle("📈 数据分析结果")
                .setMessage(analysisResult)
                .setPositiveButton("确定", null)
                .setNegativeButton("导出报告", (dialog, which) -> {
                    try {
                        // 获取当前显示的历史记录
                        List<SignalRecord> records = historyService.getAllRecords();
                        String analysisType = "signal_quality_analysis";
                        
                        // 使用本地导出方法
                        String reportPath = exportService.exportAnalysisReportLocally(records, analysisType);
                        Toast.makeText(getContext(), "分析报告已导出: " + reportPath, Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Toast.makeText(getContext(), "导出报告失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .show();
        } catch (Exception e) {
            android.util.Log.e("HistoryFragment", "Error showing analysis dialog: " + e.getMessage(), e);
            Toast.makeText(getContext(), "显示分析结果失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示图表
     */
    private void showCharts() {
        if (signalRecords == null || signalRecords.isEmpty()) {
            Toast.makeText(getContext(), "没有数据可显示图表", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(getContext(), com.example.handheld4_gsignal_app.ui.activities.ChartActivity.class);
        
        // 将当前搜索的数据直接传递给ChartActivity
        intent.putExtra("use_passed_data", true);
        intent.putExtra("data_count", signalRecords.size());
        
        // 传递过滤条件信息
        String filter = filterSpinner.getSelectedItem().toString();
        intent.putExtra("filter_type", filter);
        
        // 将SignalRecord列表序列化为JSON字符串传递
        Gson gson = new Gson();
        String jsonData = gson.toJson(signalRecords);
        intent.putExtra("signal_data", jsonData);
        
        startActivity(intent);
    }

    /**
     * 根据过滤器刷新数据
     */
    private void refreshData() {
        int selectedPosition = filterSpinner.getSelectedItemPosition();
        String filter = filterSpinner.getSelectedItem().toString();
        
        if (historyService != null) {
            // 根据过滤器设置时间范围
            String startTime = null;
            String endTime = null;
            
            switch (filter) {
                case "今天":
                    startTime = getTodayStartTime();
                    endTime = getTodayEndTime();
                    break;
                case "本周":
                    startTime = getWeekStartTime();
                    endTime = getWeekEndTime();
                    break;
                case "本月":
                    startTime = getMonthStartTime();
                    endTime = getMonthEndTime();
                    break;
                default:
                    // 全部数据，不设置时间限制
                    break;
            }
            
            // 从服务器获取过滤后的数据
            String deviceId = "DEVICE_001";
            int limit = 100;
            int offset = 0;
            
            historyService.fetchHistoryDataFromServer(deviceId, startTime, endTime, limit, offset,
                    new HistoryService.HistoryCallback() {
                @Override
                public void onSuccess(List<SignalRecord> records) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            signalRecords = records;
                            updateHistoryList();
                            updateStatistics();
                        });
                    }
                }
                
                @Override
                public void onError(String error) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "刷新数据失败: " + error, Toast.LENGTH_SHORT).show();
                            // 如果服务器查询失败，使用本地数据
                            switch (filter) {
                                case "今天":
                                    signalRecords = historyService.getTodayRecords();
                                    break;
                                case "本周":
                                    signalRecords = historyService.getWeekRecords();
                                    break;
                                case "本月":
                                    signalRecords = historyService.getMonthRecords();
                                    break;
                                default:
                                    signalRecords = historyService.getAllRecords();
                                    break;
                            }
                            updateHistoryList();
                            updateStatistics();
                        });
                    }
                }
            });
        }
    }
    
    /**
     * 获取今天的开始时间 (ISO 8601格式)
     */
    private String getTodayStartTime() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd 00:00:00", java.util.Locale.getDefault());
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        return sdf.format(new java.util.Date());
    }
    
    /**
     * 获取今天的结束时间 (ISO 8601格式)
     */
    private String getTodayEndTime() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd 23:59:59", java.util.Locale.getDefault());
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        return sdf.format(new java.util.Date());
    }
    
    /**
     * 获取本周的开始时间 (ISO 8601格式)
     */
    private String getWeekStartTime() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.MONDAY);
        cal.set(java.util.Calendar.HOUR_OF_DAY, 0);
        cal.set(java.util.Calendar.MINUTE, 0);
        cal.set(java.util.Calendar.SECOND, 0);
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        return sdf.format(cal.getTime());
    }
    
    /**
     * 获取本周的结束时间 (ISO 8601格式)
     */
    private String getWeekEndTime() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        return sdf.format(new java.util.Date());
    }
    
    /**
     * 获取本月的开始时间 (ISO 8601格式)
     */
    private String getMonthStartTime() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
        cal.set(java.util.Calendar.HOUR_OF_DAY, 0);
        cal.set(java.util.Calendar.MINUTE, 0);
        cal.set(java.util.Calendar.SECOND, 0);
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        return sdf.format(cal.getTime());
    }
    
    /**
     * 获取本月的结束时间 (ISO 8601格式)
     */
    private String getMonthEndTime() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        return sdf.format(new java.util.Date());
    }
}